# -*- coding: utf-8 -*-

class InventoryController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter ,:except =>[:hxListForInventory,:newInventory,:editInventory,:auditInventory,:refreshGainsLosses,:commonReport,:cost_price,:getInventoryInfoForCommonReport]
  after_filter :sys_after_log

  #盘点分析决策
  def analysis

  end
  
  #为系统权限服务的空方法
  def inventoryList

  end

  #为系统权限服务的空方法
  def inventoryAuditList

  end

  #为系统权限服务的空方法
  def newInventory

  end

  #显示编辑期订单的页面
  def editInventory

  end

  #为系统权限服务的空方法
  def auditInventory

  end

  def getAllInventories
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      paramsHash[:offset] = params[:start].to_i
      paramsHash[:limit] = params[:limit].to_i
      conditionsStr = ''

      if params[:order_number].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'seq_number in (:order_number)'
        else
          conditionsStr = conditionsStr + ' AND seq_number in (:order_number)'
        end
        conditionsHash[:order_number] = params[:order_number].split(/,/)
      end

      if params[:vendor_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'vendor_id = :vendor_id'
        else
          conditionsStr = conditionsStr+' AND vendor_id = :vendor_id'
        end
        conditionsHash[:vendor_id] = params[:vendor_id].to_i
      end

      if params[:to_warehouse_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'warehouse_id = :warehouse_id'
        else
          conditionsStr = conditionsStr+' AND warehouse_id = :warehouse_id'
        end
        conditionsHash[:warehouse_id] = params[:to_warehouse_id].to_i
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date <= :end_date'
        else
          conditionsStr = conditionsStr+' AND action_date <= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      #产品
      if params[:product_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'inventory_details.product_id = :product_id'
        else
          conditionsStr = conditionsStr+' AND inventory_details.product_id = :product_id'
        end
        conditionsHash[:product_id] = params[:product_id].to_i
      end
      
      logger.info conditionsStr
      count = Inventory.countAllInventories conditionsStr,conditionsHash
      inventories = Inventory.findAllInventories conditionsStr,conditionsHash,paramsHash

      jsonStr="{totalProperty:"+count.to_s+",root:"+inventories.to_json(:include=>[:employee,:department,:vendor,:auditor,:warehouse])+"}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #根据审批状态得到所有期初单据
  def getAllInventoriesByAuditStatus
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = "auditing_status like :auditing_status"
    conditionsHash[:auditing_status] = "%#{Constants::APPLY}%"

    if params[:order_number].to_s != ''
      conditionsStr = conditionsStr + ' AND seq_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:vendor_id].to_s != ''
      conditionsStr = conditionsStr+' AND vendor_id = :vendor_id'
      conditionsHash[:vendor_id] = params[:vendor_id].to_i
    end

    if params[:to_warehouse_id].to_s != ''
      conditionsStr = conditionsStr+' AND warehouse_id = :warehouse_id'
      conditionsHash[:warehouse_id] = params[:to_warehouse_id].to_i
    end

    if params[:begin_date].to_s != ''
      conditionsStr = conditionsStr+' AND action_date >= :begin_date'
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      conditionsStr = conditionsStr+' AND action_date <= :end_date'
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    count = Inventory.countAllInventories conditionsStr,conditionsHash
    inventories = Inventory.findAllInventories conditionsStr,conditionsHash,paramsHash

    jsonStr="{totalProperty:"+count.to_s+",root:"+inventories.to_json(:include=>[:employee,:department,:vendor,:auditor])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #创建新的期初单据
  def create
    paramsHash = Util.paramsPreprocessToHash(params[:data])

    info = nil
    #插入products信息
    productsHashArray = paramsHash["products"]
    productIdArray = Array.new
    productsHashArray.each do |productHash|
      #只有当用户选择的产品不为空时，才有详细订单。
      if productHash["product_id"] !=""
        productIdArray << productHash["product_id"]
      end
    end
    #从这儿开始检查一下有没有在同仓，同日期有相同产品存在的情况。如果有，再作进一步处理，取得详细的产品编号等信息
    #products = Inventory.all(:conditions=>["company_id = ? AND warehouse_id = ? AND action_date = ? AND product_id in (?)",session[:company_id],paramsHash['warehouse_id'],paramsHash['action_date'],productIdArray.join(',')])
    products = Inventory.all(:select=>"i.id,id.product_id,p.name as product_name,p.number as number",:joins =>"i left join inventory_details id on i.id = id.inventory_id AND i.vendor_id = #{paramsHash['vendor_id']} AND i.warehouse_id = #{paramsHash['warehouse_id']} AND i.action_date = '#{paramsHash['action_date']}'
left join products p on p.id = id.product_id where id.product_id in (#{productIdArray.join(',')})")
    #这儿要插入一段，用来检查是不是有同仓库，同盘点日期，同产品ID的产品存在。在盘点中，不允许同时日期，同仓库，同时产品ID的产品存在。
    if products.length > 0
      info = "产品重复"
      #如果有产品重复，则求出产品重复的产品的名称
      productStr = nil
      products.each do |product|
        if productStr == nil
          productStr = product.product_name + ":" + product.number + ","
        else
          productStr = productStr + "<br>" + product.product_name + ":" + product.number + ","
        end        
      end
      productStr = productStr[0,productStr.size-1]
      info = "您有以下产品在相同的供应商、仓库、盘点日期条件下与其它盘点记录相比重复：<br>"+productStr
    else
      inventory = Inventory.new
      inventory.company_id = session[:company_id]
      inventory.department_id = session[:department_id]
      inventory.employee_id = session[:employee_id]
      inventory.vendor_id = paramsHash['vendor_id']
      inventory.warehouse_id = paramsHash['warehouse_id']
      inventory.linkman = paramsHash['linkman']
      inventory.phone = paramsHash['phone']
      inventory.tax_rate = paramsHash['tax_rate']
      inventory.action_date = paramsHash['action_date']
      inventory.description = paramsHash['description']
      #判断一下当前用户角色是否需求审批
      sysParam =  SysParam.find_by_company_id(session[:company_id])

      #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
      if paramsHash['temporary'] == '1'
        inventory.deal_with_status = Constants::TEMP_ADD
      else
        if sysParam.audit_for_inventory_add == "否"
          inventory.auditing_status = Constants::PASS_APPLY_ADD
          inventory.deal_with_status = ''
        else
          inventory.auditing_status = Constants::AUDIT_APPLY_ADD
        end
      end


      productsHashArray.each do |productHash|
        #只有当用户选择的产品不为空时，才有详细订单。
        if productHash["product_id"] !=""
          inventoryDetail = InventoryDetail.new
          inventoryDetail.product_id = productHash["product_id"]
          inventoryDetail.quantity = productHash["quantity"]
          inventoryDetail.unit_price = productHash["unit_price"]
          inventoryDetail.amount = productHash["amount"]
          inventory.amount = inventory.amount + inventoryDetail.amount #计算订单总金额
          inventoryDetail.description = productHash["description"]
          inventory.inventory_details << inventoryDetail
        end
      end
      #inventory.save

      #开始事务，确保在流水号正常的情况下，保存销售订单,一但出现问题，则循环执行
      begin
        Sequence.transaction do
          #开始为销售订单取得流水号
          sequence = Sequence.where("company_id = ? AND sub_type = ?",session[:company_id],Inventory.name).first

          sequence.seq_no = sequence.seq_no + 1
          inventory.seq_number = sequence.seq_no
          inventory.order_number = sequence.ab + ":" + inventory.seq_number.to_s + ":" + Date.today.to_s
          sequence.save!
          inventory.save!

          #如果不需要审批，则直接提交到汇总表
          #把数据一个个的插入到结算表中。
          if paramsHash['temporary'] != '1' && sysParam.audit_for_inventory_add == "否"
            inventoryDetails = inventory.inventory_details
            inventoryDetails.each do |inventoryDetail|
              productCollection = ProductCollection.new
              productCollection.company_id = inventory.company_id
              productCollection.department_id = inventory.department_id
              productCollection.employee_id = inventory.employee_id
              productCollection.vendor_id = inventory.vendor_id
              productCollection.warehouse_id = inventory.warehouse_id
              productCollection.product_id = inventoryDetail.product_id
              productCollection.quantity =  inventoryDetail.quantity
              productCollection.description =  inventoryDetail.description
              productCollection.action_date = inventory.action_date
              productCollection.resource_id =  inventory.id
              productCollection.resource_type =  Inventory.name
              productCollection.save!
            end
          end
        end
      rescue ActiveRecord::StaleObjectError
        #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
        #这里特别指序号产生表。
        logger.info "somebody using sn before yours.............................................................."
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
        retry
      rescue ActiveRecord::RecordNotFound
        logger.info "RecordNotFound................................................................................"
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
      rescue Exception => e
        logger.info "logging......................................................................................."
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
        logger.info e
      end
      info="成功"
    end
    
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def update
    
    data = params[:data]
    info = nil
    begin
      paramsHash = Util.paramsPreprocessToHash(params[:data])
      
      inventory = Inventory.where("id = ? AND company_id = ? AND is_locked <> 1 AND auditing_status not like ?",paramsHash['id'],session[:company_id],'通过').first
      if inventory != nil
        if inventory.lock_version > paramsHash['lock_version'].to_i
          info="有其它用户在您保存之前编辑过此期初订单记录，请从新编辑！"
          result = "{success:true,info:'#{info}'}"
          render :text=>result, :layout=>false and return false
        end

        #插入products信息
        productsHashArray = paramsHash["products"]
        productIdArray = Array.new
        productsHashArray.each do |productHash|
          #只有当用户选择的产品不为空时，才有详细订单。
          if productHash["product_id"] !=""
            productIdArray << productHash["product_id"]
          end
        end
        #从这儿开始检查一下有没有在同仓，同日期有相同产品存在的情况。如果有，再作进一步处理，取得详细的产品编号等信息
        #products = Inventory.all(:conditions=>["company_id = ? AND warehouse_id = ? AND action_date = ? AND product_id in (?)",session[:company_id],paramsHash['warehouse_id'],paramsHash['action_date'],productIdArray.join(',')])
        products = Inventory.all(:select=>"i.id,id.product_id,p.name as product_name,p.number as number",:joins =>"i left join inventory_details id on i.id = id.inventory_id AND i.vendor_id = #{paramsHash['vendor_id']} AND i.warehouse_id = #{paramsHash['warehouse_id']} AND i.action_date = '#{paramsHash['action_date']}' AND i.id <> #{inventory.id}
left join products p on p.id = id.product_id where id.product_id in (#{productIdArray.join(',')})")
        #这儿要插入一段，用来检查是不是有同仓库，同盘点日期，同产品ID的产品存在。在盘点中，不允许同时日期，同仓库，同时产品ID的产品存在。
        #这儿要插入一段，用来检查是不是有同仓库，同盘点日期，同产品ID的产品存在。在盘点中，不允许同时日期，同仓库，同时产品ID的产品存在。
        if products.length > 0
          info = "产品重复"
          #如果有产品重复，则求出产品重复的产品的名称
          productStr = nil
          products.each do |product|
            if productStr == nil
              productStr = product.product_name + ":" + product.number + ","
            else
              productStr = productStr + "<br>" + product.product_name + ":" + product.number + ","
            end
          end
          productStr = productStr[0,productStr.size-1]
          info = "您有以下产品在相同的供应商、仓库、盘点日期条件下与其它盘点记录相比重复：<br>"+productStr          
        else      
          inventory.company_id = session[:company_id]
          inventory.department_id = session[:department_id]
          inventory.employee_id = session[:employee_id]
          inventory.vendor_id = paramsHash['vendor_id']
          inventory.linkman = paramsHash['linkman']
          inventory.phone = paramsHash['phone']
          inventory.tax_rate = paramsHash['tax_rate']
          inventory.action_date = paramsHash['action_date']
          inventory.description = paramsHash['description']

          inventory.audit_opinion = ''
          inventory.auditor_id = ''

          #判断一下当前用户角色是否需求审批
          sysParam =  SysParam.find_by_company_id(session[:company_id])

          #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
          if paramsHash['temporary'] == '1'
            inventory.deal_with_status = Constants::TEMP_ADD
          else
            if sysParam.audit_for_inventory_add == "否"
              if inventory.auditing_status == Constants::AUDIT_APPLY_ADD
                inventory.auditing_status = Constants::PASS_APPLY_ADD
              else
                inventory.auditing_status = Constants::PASS_APPLY_EDIT
              end
              inventory.deal_with_status = ''
            else
              if inventory.auditing_status == Constants::AUDIT_APPLY_ADD
                inventory.auditing_status = Constants::AUDIT_APPLY_ADD
              elsif
                inventory.auditing_status = Constants::AUDIT_APPLY_EDIT
              end
            end
          end

          #在这里，要作一个增，删，编辑操作，以前台数据为准。
          #首先各取出前台与后台的ID数组
          fgIdArray = Array.new
          productsHashArray.each do |productHash|
            fgIdArray << productHash["id"].to_i
          end

          bgIdArray = Array.new
          inventoryDetails = inventory.inventory_details
          inventoryDetails.each do |inventoryDetail|
            bgIdArray << inventoryDetail.id
          end

          idIntersectionArray = fgIdArray & bgIdArray
          addIdArray = fgIdArray - idIntersectionArray
          delIdArray = bgIdArray - idIntersectionArray
          InventoryDetail.delete(delIdArray)

          #在进行从新整理数据之前，先把采购订单的总金额置“0”
          inventory.amount = 0
          productsHashArray.each do |productHash|
            #只有当用户选择的产品不为空时，才有详细订单。
            if productHash["product_id"] !=""
              #没Id说明是新增加的。
              if productHash["id"] == ""
                inventoryDetail = InventoryDetail.new
                inventoryDetail.product_id = productHash["product_id"]
                inventoryDetail.quantity = productHash["quantity"]
                inventoryDetail.unit_price = productHash["unit_price"]
                inventoryDetail.amount = productHash["amount"]
                inventory.amount = inventory.amount + inventoryDetail.amount #计算订单总金额
                inventoryDetail.description = productHash["description"]
                inventory.inventory_details << inventoryDetail
              else
                inventoryDetail = InventoryDetail.find(productHash["id"].to_i)
                inventoryDetail.product_id = productHash["product_id"]
                inventoryDetail.quantity = productHash["quantity"]
                inventoryDetail.unit_price = productHash["unit_price"]
                inventoryDetail.amount = productHash["amount"]
                inventory.amount = inventory.amount + inventoryDetail.amount #计算订单总金额
                inventoryDetail.description = productHash["description"]
                inventoryDetail.save
              end
            end
          end
          inventory.save!

          #把数据一个个的插入到结算表中。如果是不需要审批的，直接插入结算表中。
          if paramsHash['temporary'] != '1' && sysParam.audit_for_inventory_add == "否"
            #先删除以前的记录，此处处理是为了防止sysparams变化引起多余的数据。
            ProductCollection.delete_all("resource_type = 'Inventory' AND resource_id = #{params[:inventory_id]}")

            inventoryDetails = inventory.inventory_details
            inventoryDetails.each do |inventoryDetail|
              productCollection = ProductCollection.new
              productCollection.company_id = inventory.company_id
              productCollection.department_id = inventory.department_id
              productCollection.employee_id = inventory.employee_id
              productCollection.vendor_id = inventory.vendor_id
              productCollection.warehouse_id = inventory.warehouse_id
              productCollection.product_id = inventoryDetail.product_id
              productCollection.quantity =  inventoryDetail.gl_quantity
              productCollection.description =  inventoryDetail.description
              productCollection.action_date = inventory.action_date
              productCollection.resource_id =  inventory.id
              productCollection.resource_type =  Inventory.name
              productCollection.save!
            end
          end
          info="成功"
        end
      end      
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      logger.info "ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end


  #更新审批状态
  def updateAuditingStatus
    inventory = Inventory.find(params[:inventory_id])
    info = nil;
    begin
      if inventory !=nil
        Inventory.transaction do
          auditingStatus = params[:auditing_status]
          inventory.auditor_id = session[:employee_id]
          inventory.audit_opinion =  params[:audit_opinion]

          if(auditingStatus == "是")
            #先删除以前的记录，此处处理是为了防止sysparams变化引起多余的数据。
            ProductCollection.delete_all("resource_type = 'Inventory' AND resource_id = #{params[:inventory_id]}")

            if inventory.auditing_status == Constants::AUDIT_APPLY_ADD
              inventory.auditing_status = Constants::PASS_APPLY_ADD
            elsif inventory.auditing_status == Constants::AUDIT_APPLY_EDIT
              inventory.auditing_status = Constants::PASS_APPLY_EDIT
            elsif inventory.auditing_status == Constants::AUDIT_APPLY_CANCEL #申请撤消
              inventory.auditing_status = Constants::PASS_APPLY_CANCEL
              inventory.deal_with_status = Constants::CANCELED
            end
            inventory.save!
            #记录变更历史
            inventoryHx = InventoryHx.new
            inventoryHx.inventory_id = inventory.id
            inventoryHx.company_id = inventory.company_id
            inventoryHx.department_id = inventory.department_id
            inventoryHx.employee_id = inventory.employee_id
            inventoryHx.vendor_id = inventory.vendor_id
            inventoryHx.linkman = inventory.linkman
            inventoryHx.phone = inventory.phone
            inventoryHx.tax_rate = inventory.tax_rate
            inventoryHx.action_date = inventory.action_date
            inventoryHx.description = inventory.description
            inventoryHx.amount = inventory.amount

            inventoryHx.audit_opinion = inventory.audit_opinion
            inventoryHx.auditor_id = inventory.auditor_id

            #把数据一个个的插入到结算表中。
            inventoryDetails = inventory.inventory_details
            inventoryDetails.each do |inventoryDetail|
              productCollection = ProductCollection.new
              productCollection.company_id = inventory.company_id
              productCollection.department_id = inventory.department_id
              productCollection.employee_id = inventory.employee_id
              productCollection.vendor_id = inventory.vendor_id
              productCollection.warehouse_id = inventory.warehouse_id
              productCollection.product_id = inventoryDetail.product_id
              productCollection.quantity =  inventoryDetail.gl_quantity
              productCollection.description =  inventoryDetail.description
              productCollection.action_date = inventory.action_date
              productCollection.resource_id =  inventory.id
              productCollection.resource_type =  Inventory.name
              productCollection.save!

              #记录历史变更
              inventoryHxDetail = InventoryHxDetail.new
              inventoryHxDetail.product_id = inventoryDetail.product_id
              inventoryHxDetail.quantity =  inventoryDetail.quantity
              inventoryHxDetail.gl_quantity =  inventoryDetail.gl_quantity
              inventoryHxDetail.unit_price =  inventoryDetail.unit_price
              inventoryHxDetail.amount =  inventoryDetail.amount
              inventoryHx.inventory_hx_details << inventoryHxDetail
            end
            inventoryHx.save!
          else
            if inventory.auditing_status == Constants::AUDIT_APPLY_ADD
              inventory.auditing_status = Constants::REJECT_APPLY_ADD
            elsif inventory.auditing_status == Constants::AUDIT_APPLY_EDIT
              inventory.auditing_status = Constants::REJECT_APPLY_EDIT
            end
            inventory.save!
          end
          #结算表处理完毕。
          info = "成功"
        end
      else
        info = "失败"
      end
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    result = "{success:true,info:'#{info}'}"
    logger.info result
    render :text=>result, :layout=>false
  end

  def getInventoryDetailsById
    begin
      inventoryDetails = InventoryDetail.where(inventory_id:params[:inventory_id]).includes([:product])
      jsonStr="{totalProperty:"+inventoryDetails.length.to_s+",root:"+inventoryDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:number,:unit,:is_suit,:spec,:description]}})+"}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  def getInventoryById
    begin
      inventory = Inventory.find(params[:id])
      rootStr = inventory.to_json(:include=>{:vendor=>{:only=>[:id,:name]},:warehouse=>{:only=>[:id,:name]}})
      jsonStr = "{root:["+rootStr+"]}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #申请撤消
  def applyToCancel
    begin
      inventory = Inventory.find(params[:id])
      sysParam =  SysParam.find_by_company_id(session[:company_id])
      if sysParam.audit_for_inventory_cancel == "否"
        inventory.auditing_status = Constants::PASS_APPLY_CANCEL
        inventory.deal_with_status = Constants::CANCELED
        ProductCollection.delete_all("resource_type = 'Inventory' AND resource_id = #{params[:id]}")
        #如果不需要审核，则把汇总表中的数据设置为is_locked = 1
      else
        inventory.auditing_status = Constants::AUDIT_APPLY_CANCEL
      end
      inventory.auditor_id = session[:employee_id]
      inventory.save!
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到变更历史的摘要
  def getHxesById
    inventoryHxes = InventoryHx.where(inventory_id:params[:id]).includes([:department,:employee,:warehouse])
    jsonStr="{totalProperty:"+inventoryHxes.length.to_s+",root:"+inventoryHxes.to_json(:include=>[:department,:employee,:warehouse])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #根据变更Id得到详细信息
  def getHxDetailsByHxId
    inventoryHxDetails = InventoryHxDetail.where(inventory_hx_id:params[:id]).includes([:product])
    jsonStr="{totalProperty:"+inventoryHxDetails.length.to_s+",root:"+inventoryHxDetails.to_json(:include=>[:product])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #更新盘点记录的损益数量
  def refreshGainsLosses
    #每次更新了损益后，要设置审批状态，才可以更新到PC表中。
    begin
      inventoryId = params[:id]
      actionDate = params[:action_date]
      inventory = Inventory.find(inventoryId)
      inventoryDetails = inventory.inventory_details
      inventoryDetails.each do |inventoryDetail|
        productId = inventoryDetail.product_id
        warehouseId = inventory.warehouse_id
        actionDate = inventory.action_date
        quantity =  ProductCollection.where("product_id = ? AND warehouse_id = ? AND action_date <= ?",productId,warehouseId,actionDate).sum(:quantity)
        inventoryDetail.gl_quantity = inventoryDetail.quantity - quantity
        inventory.inventory_details << inventoryDetail
        #更新完以后从新审批审批。        
        inventory.auditing_status = Constants::AUDIT_APPLY_EDIT
      end
      inventory.save!
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到所有非取消的状态的盘点历史日期
  def getAllInventoryDate
    inventoryDate = Inventory.select("distinct action_date").where("auditing_status not like ? AND auditing_status not like ?","%#{Constants::CANCEL}%","%#{Constants::APPLY}%")
    jsonStr="{totalProperty:"+inventoryDate.length.to_s+",root:"+inventoryDate.to_json()+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #统计盘点库存产品的销售额
  def getInventoryInfoForCommonReport
    #Product.cost_price
    begin
      #begin
      conditionsStr = ''

      #处于申请或已撤消状态的订单，不计算在内。
      if conditionsStr == ''
        conditionsStr = " it.auditing_status not like '%#{Constants::APPLY}%' AND it.auditing_status not like '%#{Constants::PASS_APPLY_CANCEL}%' "
      else
        conditionsStr = conditionsStr + " AND it.auditing_status not like '%#{Constants::APPLY}%' AND it.auditing_status not like '%#{Constants::PASS_APPLY_CANCEL}%' "
      end

      if params[:vendor_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = " it.vendor_id = #{params[:vendor_id]}"
        else
          conditionsStr = conditionsStr + " AND it.vendor_id = #{params[:vendor_id]}"
        end
      end

      if params[:warehouse_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = " it.warehouse_id = #{params[:warehouse_id]}"
        else
          conditionsStr = conditionsStr + " AND it.warehouse_id = #{params[:warehouse_id]}"
        end
      end

      if params[:action_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = " it.action_date = '#{params[:action_date]}'"
        else
          conditionsStr = conditionsStr+" AND it.action_date = '#{params[:action_date]}'"
        end
      end

      if params[:product_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = " itd.product_id = '#{params[:product_id]}'"
        else
          conditionsStr = conditionsStr+" AND itd.product_id = '#{params[:product_id]}'"
        end
      end

      if conditionsStr != ""
        conditionsStr = " where " + conditionsStr
      end

      selectStr = "p.name product_name,p.number product_number,p.cost_price cost_price,sum(itd.quantity) quantity,sum(itd.quantity)*p.cost_price amount,sum(itd.gl_quantity) gl_quantity,sum(itd.gl_quantity)*p.cost_price gl_amount"

      groupByStr = " group by itd.product_id"
      if params[:vendor_id].to_s == ""
        if params[:vendor_group].to_s == 'true'
          groupByStr = groupByStr + ",it.vendor_id"
          selectStr = selectStr + ",v.name vendor_name"
        end
      end
        
      if params[:warehouse_id].to_s == ""
        if params[:warehouse_group].to_s == 'true'
          groupByStr = groupByStr + ",it.warehouse_id"
          selectStr = selectStr + ",w.name warehouse_name"
        end
      end

      inventoriesTotal = Inventory.select("it.id").joins(" it left join inventory_details itd on it.id = itd.inventory_id
                        left join products p on itd.product_id = p.id
                        left join warehouses w on w.id = it.warehouse_id
                        left join vendors v on v.id = it.vendor_id " + conditionsStr + groupByStr).order("it.id")
      
      inventoriesTotalAmount = Inventory.select("it.id,sum(itd.quantity*p.cost_price) amount,sum(itd.gl_quantity*p.cost_price) gl_amount").joins(" it
                        left join inventory_details itd on it.id = itd.inventory_id
                        left join products p on itd.product_id = p.id
                        left join warehouses w on w.id = it.warehouse_id
                        left join vendors v on v.id = it.vendor_id " + conditionsStr).order("it.id").first
      
      inventories = Inventory.select(selectStr).joins(" it left join inventory_details itd on it.id = itd.inventory_id
                        left join products p on itd.product_id = p.id
                        left join warehouses w on w.id = it.warehouse_id
                        left join vendors v on v.id = it.vendor_id " + conditionsStr + groupByStr).offset(params[:start].to_i).limit(params[:limit].to_i).order("it.id")

      #此语句主要用来求总金额与损益金额
      amountTotal = 0
      glAmountTotle = 0
      logger.info inventories.length
      if inventoriesTotalAmount != nil
        amountTotal = inventoriesTotalAmount.amount.to_f
        glAmountTotle = inventoriesTotalAmount.gl_amount.to_f
      end
      
      logger.info amountTotal
      logger.info glAmountTotle
      jsonStr="{totalProperty:"+inventoriesTotal.length.to_s+",amount:#{amountTotal.to_s},gl_amount:#{glAmountTotle.to_s},root:"+inventories.to_json()+"}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #测试计算一下产品的成本。
  def cost_price
    #    products = Product.find_by_sql("update products p inner join (select product_id,ROUND(sum(amount)/sum(quantity),2) cost_price
    #                                    from (select product_id, quantity,amount from purchase_order_details union all
    #                                                 select product_id, quantity,amount from opening_stock_details
    #                                           ) as t group by product_id) tp on tp.product_id = p.id set p.cost_price = tp.cost_price")
    #    logger.info products.to_json
    #     products = ActiveRecord::Base.connection.execute("update products p inner join (select product_id,ROUND(sum(amount)/sum(quantity),2) cost_price
    #                                    from (select product_id, quantity,amount from purchase_order_details union all
    #                                                 select product_id, quantity,amount from opening_stock_details
    #                                           ) as t group by product_id) tp on tp.product_id = p.id set p.cost_price = tp.cost_price")
    #     logger.info products
    #    logger.info products.to_json
    #Product.cost_price
  end
end
